package com.yl.users.entity

import com.alibaba.fastjson.JSONObject
import com.baomidou.mybatisplus.annotation.*
import com.yl.common.Flag
import com.yl.common.UserType
import com.yl.common.annotation.NoArg
import java.util.*
import java.util.concurrent.ConcurrentHashMap

/**
 *
 * create by 2021/5/14.
 * @author udbjqr
 */
@NoArg
@TableName("sys_company")
data class SysCompany(
	@TableId(value = "id", type = IdType.AUTO)
	var id: Long,
	@TableField(value = "name", condition = SqlCondition.LIKE)
	var name: String,
	@TableField("create_user_id")
	var createUserId: Long? = null,
	@TableField("create_time")
	var createTime: Date = Date(),
	@TableField("update_user_id")
	var updateUserId: Long? = null,
	@TableField("update_time")
	var updateTime: Date = Date(),
	@TableField("enabled")
	var enabled: Int? = 1,


	@TableField("super_id")
	var superId: Long? = null,
	@TableField(exist = false)
	var superior: SysCompany? = null,
	/**
	 * 发送配置
	 * json字符
	 * {
	 * //公司用户
	 *  userType：{
	 *  sendType: 1,选中全部发送，2，按顺序发送 SendType
	 *  messageType: 逗号隔开字符串 messageType.value
	 *  }
	 * }
	 */
	@TableField("send_configuration")
	var sendConfiguration: String? = null,

	/**
	 * 推送配置
	 *  {
	 *          messageName:{
	 *              按需配置
	 *          }
	 *  }
	 */
	@TableField("message_configuration")
	var messageConfiguration: String? = null,

	@TableField("flag")
	var flag: Flag = Flag.UNKNOWN,
) {
	@TableField(exist = false)
	private var _users: ConcurrentHashMap<Long, CompanyUser>? = null


	val users: ConcurrentHashMap<Long, CompanyUser>
		get() {
			if (_users == null) {
				_users = ConcurrentHashMap()
			}

			return _users!!
		}


	fun getSendType(userType: UserType): Int {
		if (sendConfiguration == null) {
			return 1
		}
		val body = JSONObject.parseObject(sendConfiguration)
		val jsonObject = body.getJSONObject(userType.show) ?: return 1
		val intValue = jsonObject.getIntValue("sendType")
		if (intValue == 0) {
			return 1
		}
		return intValue
	}

	fun getSendMessageTypes(userType: UserType): List<String> {
		if (sendConfiguration == null) {
			return listOf()
		}
		val body = JSONObject.parseObject(sendConfiguration)
		val jsonObject = body.getJSONObject(userType.show) ?: return listOf()
		val typeStr = jsonObject.getString("messageType") ?: return listOf()
		val split = typeStr.split(",")
		val list = mutableListOf<String>()
		for (s in split) {
			list.add(s)
		}
		return list
	}

	@TableField(exist = false)
	private var messageConfig: JSONObject? = null
	fun getMessageConfig(messageName: String): JSONObject? {
		return if (messageConfig == null) {
			messageConfig = JSONObject.parseObject(messageConfiguration ?: return null)
			messageConfig!!.getJSONObject(messageName)
		} else {
			messageConfig!!.getJSONObject(messageName)
		}
	}
}
